package com.cmes.web.trace;

import com.cmes.core.context.security.SecurityContextHolder;
import com.cmes.core.utils.StringPool;
import com.cmes.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自动生成 traceId，设置 MDC 并设置至上下文
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
public class TraceFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String traceId = request.getHeader("traceId");
            if (StringUtils.isEmpty(traceId)) {
                traceId = StringUtils.uuid();
            }
            SecurityContextHolder.setTraceId(traceId);
            MDC.put("traceId", traceId);
            filterChain.doFilter(request, response);
        } finally {
            SecurityContextHolder.setToken(StringPool.EMPTY);
            MDC.remove("traceId");
        }
    }

}
